﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

public class MyAESTools2
{
    public static string AESKey = "dKeH+OljdZRh/X8twhuI=kw55aSAvlkQ";

    public static string Encrypt(string plainText, string AESKey)
    {
        try
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 
            rijndaelCipher.Key = Encoding.UTF8.GetBytes(AESKey);//加解密双方约定好密钥：AESKey
            rijndaelCipher.GenerateIV();
            byte[] keyIv = rijndaelCipher.IV;
            byte[] cipherBytes = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cipherBytes = ms.ToArray();//得到加密后的字节数组
                    cs.Close();
                    ms.Close();
                }
            }
            var allEncrypt = new byte[keyIv.Length + cipherBytes.Length];
            Buffer.BlockCopy(keyIv, 0, allEncrypt, 0, keyIv.Length);
            Buffer.BlockCopy(cipherBytes, 0, allEncrypt, keyIv.Length * sizeof(byte), cipherBytes.Length);
            return Convert.ToBase64String(allEncrypt);
        }
        catch
        {
            return "";
        }
    }

    public static string Decrypt(string showText, string AESKey)
    {
        string result = string.Empty;
        try
        {
            byte[] cipherText = Convert.FromBase64String(showText);
            int length = cipherText.Length;
            SymmetricAlgorithm rijndaelCipher = Rijndael.Create();
            rijndaelCipher.Key = Encoding.UTF8.GetBytes(AESKey);//加解密双方约定好的密钥
            byte[] iv = new byte[16];
            Buffer.BlockCopy(cipherText, 0, iv, 0, 16);
            rijndaelCipher.IV = iv;
            byte[] decryptBytes = new byte[length - 16];
            byte[] passwdText = new byte[length - 16];
            Buffer.BlockCopy(cipherText, 16, passwdText, 0, length - 16);
            using (MemoryStream ms = new MemoryStream(passwdText))
            {
                using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            result = Encoding.UTF8.GetString(decryptBytes).Replace("\0", "");   ///将字符串后尾的'\0'去掉
        }
        catch { }
        return result;
    }

    public static string DoEncrypt(string plainText)
    {
        return Encrypt(plainText, AESKey);
    }

    public static string DoDecrypt(string showText)
    {
        return Decrypt(showText, AESKey);
    }

}

